// utils/priorityWorkerManager.js
class PriorityWorkerManager {
    constructor() {
        this.worker = null;
        this.callbacks = new Map();
        this.messageId = 0;
    }

    init() {
        if (this.worker) return;

        this.worker = new Worker(new URL('../workers/priorityWorker.js', 
            import.meta.url));

        this.worker.onmessage = (e) => {
            const { type, data, messageId } = e.data;
            const callback = this.callbacks.get(messageId);
            
            if (callback) {
                callback.resolve(data);
                this.callbacks.delete(messageId);
            }
        };

        this.worker.onerror = (error) => {
            console.error('Priority Worker error:', error);
            this.callbacks.forEach(callback => callback.reject(error));
            this.callbacks.clear();
        };
    }

    async calculatePriorities(objects, viewportCenter) {
        if (!this.worker) {
            this.init();
        }

        const messageId = this.messageId++;

        // 只传递必要的数据，不传递整个对象
        const simplifiedObjects = objects.map(obj => ({
            id: obj.id,
            left: obj.left,
            top: obj.top,
            width: obj.width,
            height: obj.height
        }));

        return new Promise((resolve, reject) => {
            this.callbacks.set(messageId, { resolve, reject });

            this.worker.postMessage({
                type: 'calculatePriorities',
                data: { 
                    objects: simplifiedObjects, 
                    viewportCenter 
                },
                messageId
            });
        });
    }

    terminate() {
        if (this.worker) {
            this.worker.terminate();
            this.worker = null;
            this.callbacks.clear();
        }
    }
}

const priorityWorkerManager = new PriorityWorkerManager();
export default priorityWorkerManager;